package com.akupilih.app;

import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.akupilih.app.model.DBClass;
import com.akupilih.app.model.Utils;
import com.akupilih.app.model.WebService;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.facebook.HttpMethod;
import com.facebook.LoggingBehavior;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.Settings;

public class VoteFragment extends Fragment implements OnClickListener {

	ImageView Prabowo, Jokowi;
	String Voted = "0";
	Button btnVote;
	private boolean isLogin = false;
	private Session.StatusCallback statusCallback = new SessionStatusCallback();

	private FragmentActivity myContext;
	private HashMap<String, String> params;
	private ProgressDialog pDialog;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		pDialog = new ProgressDialog(getActivity());
		pDialog.setMessage("Loading...");

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View rootView = inflater.inflate(R.layout.fragment_vote, container,
				false);

		Prabowo = (ImageView) rootView.findViewById(R.id.vote_prabowo);
		Jokowi = (ImageView) rootView.findViewById(R.id.vote_jokowi);
		btnVote = (Button) rootView.findViewById(R.id.btnVote);
		DBClass db = new DBClass(getActivity());
		if (db.cekVoted()) {
			btnVote.setText("Lihat Hasil");
		}
		Settings.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);

		Session session = Session.getActiveSession();
		if (session == null) {
			if (savedInstanceState != null) {
				session = Session.restoreSession(getActivity(), null,
						statusCallback, savedInstanceState);
			}
			if (session == null) {
				session = new Session(getActivity());
			}
			Session.setActiveSession(session);
			if (session.getState().equals(SessionState.CREATED_TOKEN_LOADED)) {
				session.openForRead(new Session.OpenRequest(this)
						.setCallback(statusCallback));
			}
		}

		updateState();

		if (db.getVote().equals("1")) {
			Prabowo.setImageResource(R.drawable.vote_prabowo_on);
		}

		if (db.getVote().equals("2")) {
			Jokowi.setImageResource(R.drawable.vote_jokowi_on);
		}

		Prabowo.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Prabowo.setImageResource(R.drawable.vote_prabowo_on);
				Jokowi.setImageResource(R.drawable.vote_jokowi_off);
				Voted = "1";
			}
		});
		Jokowi.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Prabowo.setImageResource(R.drawable.vote_prabowo_off);
				Jokowi.setImageResource(R.drawable.vote_jokowi_on);
				Voted = "2";
			}
		});

		btnVote.setOnClickListener(this);

		return rootView;
	}

	@Override
	public void onStart() {
		super.onStart();
		Utils.TRACE("VoteFragment", "onStart : ");
		Session.getActiveSession().addCallback(statusCallback);
	}

	@Override
	public void onStop() {
		super.onStop();
		Utils.TRACE("VoteFragment", "onStop : ");
		Session.getActiveSession().removeCallback(statusCallback);
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		Utils.TRACE("VoteFragment", "onActivityResult : ");
		Session.getActiveSession().onActivityResult(getActivity(), requestCode,
				resultCode, data);
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		Session session = Session.getActiveSession();
		Session.saveSession(session, outState);
	}

	/**
	 * get data user fb
	 * 
	 * @param session
	 */
	private void getUserData(Session session) {
		new com.facebook.Request(session, "/me", null, HttpMethod.GET,
				new com.facebook.Request.Callback() {

					@Override
					public void onCompleted(com.facebook.Response response) {
						JSONObject jsonObject = null;
						try {
							jsonObject = new JSONObject(response
									.getGraphObject().getInnerJSONObject()
									.toString());
							Utils.TRACE(
									"MainActivity.getUserData(...).new Callback() {...}",
									"onCompleted : " + jsonObject.toString());
							Utils.setDataStringToSP(getActivity(),
									Utils.PREF_FB_ID,
									jsonObject.getString("id"));
							Utils.setDataStringToSP(getActivity(),
									Utils.PREF_USERNAME,
									jsonObject.getString("name"));

							// Toast.makeText(getActivity(),
							// "name : " + jsonObject.getString("name"),
							// Toast.LENGTH_SHORT).show();
							// Toast.makeText(getActivity(),
							// "id : " + jsonObject.getString("id"),
							// Toast.LENGTH_SHORT).show();
						} catch (JSONException e) {
							Utils.TRACE(
									"MainActivity.getUserData(...).new Callback() {...}",
									"onCompleted : " + e.getMessage());
						}
					}
				}).executeAsync();
	}

	private class SessionStatusCallback implements Session.StatusCallback {
		@Override
		public void call(Session session, SessionState state,
				Exception exception) {
			updateState();
		}
	}

	/**
	 * update state login/not
	 */
	public void updateState() {
		Session session = Session.getActiveSession();
		if (session.isOpened()) {
			Utils.TRACE("VoteFragment", "updateState : user login");
			isLogin = true;
			getUserData(session);
		} else {
			Utils.TRACE("VoteFragment", "updateState : user not login");
			isLogin = false;
		}

	}

	@Override
	public void onClick(View v) {
		DBClass db = new DBClass(getActivity());
		// TODO Auto-generated method stub
		if (v == btnVote) {
			if (Voted.equals("0") && !db.cekVoted()) {
				Toast.makeText(getActivity(), "Tidak boleh golput :p",
						Toast.LENGTH_SHORT).show();
			} else {
				if (isLogin && !db.cekVoted()) {
					params = new HashMap<String, String>();
					params.put(
							"fbid",
							""
									+ Utils.getDataStringFromSP(getActivity(),
											Utils.PREF_FB_ID));
					params.put(
							"nama",
							""
									+ Utils.getDataStringFromSP(getActivity(),
											Utils.PREF_USERNAME));
					params.put("vote", "" + Voted);

					sentDataVote(WebService.DO_VOTE());

					Toast.makeText(getActivity(), "Vote :" + Voted,
							Toast.LENGTH_SHORT).show();
					Intent i = new Intent(getActivity(),
							VoteHasilActivity.class);
					startActivity(i);
				} else {
					Session session = Session.getActiveSession();
					if (!session.isOpened() && !session.isClosed())
						session.openForRead(new Session.OpenRequest(this)
								.setCallback(statusCallback));
					else
						Session.openActiveSession(getActivity(), this, true,
								statusCallback);
				}
			}
		}
	}

	private void sentDataVote(String URL) {
		final DBClass db = new DBClass(getActivity());
		StringRequest request = new StringRequest(Request.Method.POST, URL,
				new Response.Listener<String>() {
					@Override
					public void onResponse(String arg0) {
						try {
							pDialog.dismiss();
							Utils.TRACE(
									"VoteFragment.sentDataVote(...).new Listener() {...}",
									"onResponse : " + arg0);
							JSONObject object = new JSONObject(arg0);
							// olah data after submit vote

							db.addVote(Voted);

							Intent i = new Intent(getActivity(),
									VoteHasilActivity.class);
							startActivity(i);

						} catch (JSONException e) {
							Utils.TRACE(
									"VoteFragment.sentDataVote(...).new StringRequest() {...}",
									"sentDataVote : " + e.getMessage());
						}
					}
				}, new Response.ErrorListener() {
					@Override
					public void onErrorResponse(VolleyError arg0) {
						Utils.TRACE(
								"VoteFragment.sentDataVote(...).new StringRequest() {...}",
								"sentDataVote : " + arg0.toString());
						pDialog.dismiss();
					}
				}) {
			@Override
			protected Map<String, String> getParams() throws AuthFailureError {
				return params;
			}
		};
		pDialog.show();
		BaseApplication.getInstance().addToRequestQueue(request, "VOTE");
	}

}
